$().ready(function() {
	
	$('.button-add-amount').live('click', function(e) {
		e.stopPropagation();
		_value = parseInt($('#amount').val());
		_id_structure = ($('#ihm-content-listing li.selected').attr('parent')) ? $('#ihm-content-listing li.selected').attr('parent') : 0;
		_url = $(this).attr('href');
		if (_url) {
			$.ajax({
				url:_url, 
				data:'amount='+ _value + '&id_structure=' + _id_structure, 
				success: function(message) {
					$('.point-system').html(message);
				},
				complete: function() {
					//TODo: script fermeture
					$('.point-system').parents('.element').eq(0).each(function() {
						if ($(this).attr('old-query')) {
							$e = $(this);
							//refresh
							$.ajax({
								async:false,
								url: $(this).attr('old-query'),
								success: function(msg) {
									$e.html(msg);
								},
								error: function() {
									$('.path-element').eq($('.path-element').length-2).click();
								}
							});
						}
					});
				}
			});
		}
		return false;
	});
	
	// increase
	$('.point-increase').live('click', function(e) {
		e.stopPropagation();
		_value = '';
		$('.point-system span').each(function() {
			_value += $(this).html();
		});
		_old = parseInt($('#old-points').val());
		
		_value = parseInt(_value) + 1;
		_string = _value.toString();
		_diff = 6-_string.length;
		_span = '';
		if (_diff > 0) {
			while(_diff) {
				_span += '<span></span>';
				_diff--;
			}
		}
		
		for(i=0;i<=_string.length-1;i++) {
			_span += '<span>'+ _string.substr(i, 1) +'</span>';
		}
		$('.point-system').html(_span);
		$('#amount').val(_value-_old);
		return false;
	});
	
	//decrease
	$('.point-decrease').live('click', function(e) {
		e.stopPropagation();
		_value = '';
		$('.point-system span').each(function() {
			_value += $(this).html();
		});
		_old = parseInt($('#old-points').val());
		
		
		_value = parseInt(_value) - 1;
		_string = _value.toString();
		_diff = 6-_string.length;
		_span = '';
		if (_diff > 0) {
			while(_diff) {
				_span += '<span></span>';
				_diff--;
			}
		}
		
		for(i=0;i<=_string.length-1;i++) {
			_span += '<span>'+ _string.substr(i, 1) +'</span>';
		}
		$('.point-system').html(_span);
		$('#amount').val(_value-_old);
		return false;
	});
	
	$('#amount').live('blur', function(e) {
		e.stopPropagation();
		_old = parseInt($('#amount').val());
		_value = parseInt($('#old-points').val()) + _old;
		_string = _value.toString();
		_diff = 6-_string.length;
		_span = '';
		if (_diff > 0) {
			while(_diff) {
				_span += '<span></span>';
				_diff--;
			}
		}
		
		for(i=0;i<=_string.length-1;i++) {
			_span += '<span>'+ _string.substr(i, 1) +'</span>';
		}
		$('.point-system').html(_span);
	});
	
});
